package com.jia.springcloud.controller;


import com.jia.springcloud.entities.CommonResult;
import com.jia.springcloud.entities.Payment;
import com.jia.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 1038940655
 * @create 2021/1/19 16:35
 */
@RestController
@RequestMapping("/payment")
@Slf4j
public class PaymentController {

    @Autowired
    private PaymentService paymentService;

    @Value("${server.port}")
    private String serverPort;
    //    spring提供的一个发现微服务的一个接口
    @Autowired
    private DiscoveryClient discoveryClient;

    @RequestMapping("/create")
    public CommonResult create(@RequestBody Payment payment){
        int i = paymentService.create(payment);
        log.info("***插入结果："+ i);

        if(i > 0){
            return new CommonResult(200,"插入成功",i);
        }
        return new CommonResult(444,"插入失败");
    }

    @GetMapping("/get/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Integer id){
        Payment payment = paymentService.getPaymentById(id);
        log.info("***得到的结果："+payment);

        if (payment != null){
            return new CommonResult(200,"查询成功,serverPort:"+serverPort,payment);
        }

        return new CommonResult(444,"没有对应记录，查询id",null);
    }

    @GetMapping("/discovery")
    public Object discovery(){

        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            log.info("该注册中心中的微服务分别是："+service);
        }

        List<ServiceInstance> instances = discoveryClient.getInstances("SPRINGCLOUD-PROVIDER-PAYMENT");
        for (ServiceInstance instance : instances) {
            log.info("****instance:" + instance);

            log.info("**" + instance.getServiceId() + "\t"
                    + instance.getHost() + "\t" + instance.getPort() + "\t" + instance.getUri());
        }
        return this.discoveryClient;
    }
}
